﻿using System;

using System.Text;
using RoughJs.Error;

namespace RoughJs.Ast
{
    /// <summary>
    /// 2010-01-5 ----- 2010-01-29
    /// 陈曦 1.0
    /// Microsoft Public License (Ms-PL)
    ///This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
    ///1. Definitions
    ///The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
    ///A "contribution" is the original software, or any additions or changes to the software.
    ///A "contributor" is any person that distributes its contribution under this license.
    ///"Licensed patents" are a contributor's patent claims that read directly on its contribution.
    ///2. Grant of Rights
    ///(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
    ///(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
    ///3. Conditions and Limitations
    ///(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
    ///(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
    ///(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
    ///(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
    ///(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 
    /// 
    /// 
    /// 方法对象的基类
    /// 参看ECMA 15.3.
    /// </summary>
    public class BaseFunction : IdScriptableObject, Function
    {
        private static Object FUNCTION_TAG = "Function";

        public static void init(Scriptable scope, bool sealed1)
        {
            BaseFunction obj = new BaseFunction();
            // Function.prototype attributes: see ECMA 15.3.3.1 
            obj.prototypePropertyAttributes = DONTENUM | READONLY | PERMANENT;
            obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed1);
        }

        public BaseFunction()
        {
        }

        public BaseFunction(Scriptable scope, Scriptable prototype)
            : base(scope, prototype)
        {

        }

        public override string getClassName()
        {
            return "Function";
        }

        /// <summary>
        /// 实现Javascript function 对象的instanceof操作
        /// foo = new Foo();
        /// foo instanceof Foo;
        /// </summary>
        /// <param name="instance"></param>
        /// <returns></returns>
        public virtual bool hasInstance(Scriptable instance)
        {
            Object protoProp = ScriptableObject.getProperty(this, "prototype");
            if (protoProp is Scriptable)
            {
                return ScriptRuntime.jsDelegatesTo(instance, (Scriptable)protoProp);
            }
            throw ScriptRuntime.typeError1("msg.instanceof.bad.prototype",
                                           getFunctionName());
        }

        public override int getMaxInstanceId()
        {
            return MAX_INSTANCE_ID;
        }

        public override int findInstanceIdInfo(string s)
        {
            int id;
            // #generated# Last update: 2007-05-09 08:15:15 EDT
            id = 0; String X = null; int c;
            switch (s.Length)
            {
                case 4: X = "name"; id = Id_name; goto L;
                case 5: X = "arity"; id = Id_arity; goto L;
                case 6: X = "length"; id = Id_length; goto L;
                case 9: c = s.ToCharArray()[0];
                    if (c == 'a') { X = "arguments"; id = Id_arguments; }
                    else if (c == 'p') { X = "prototype"; id = Id_prototype; }
                    goto L;
            }
        L: ;
            if (X != null && X != s && !(X == s)) id = 0;
            goto L0;

        L0: ;
            // #/generated#
            // #/string_id_map#

            if (id == 0) return base.findInstanceIdInfo(s);

            int attr;
            switch (id)
            {
                case Id_length:
                case Id_arity:
                case Id_name:
                    attr = DONTENUM | READONLY | PERMANENT;
                    break;
                case Id_prototype:
                    attr = prototypePropertyAttributes;
                    break;
                case Id_arguments:
                    attr = DONTENUM | PERMANENT;
                    break;
                default: throw new Exception();
            }
            return instanceIdInfo(attr, id);
        }

        private const int
    Id_length = 1,
    Id_arity = 2,
    Id_name = 3,
    Id_prototype = 4,
    Id_arguments = 5;


        private static int MAX_INSTANCE_ID = 5;
/// <summary>
/// 作为不可枚举，不可删除，只读的prototype属性
/// </summary>
/// <param name="value"></param>
        public void setImmunePrototypeProperty(Object value)
        {
            if ((prototypePropertyAttributes & READONLY) != 0)
            {
                throw new Exception();
            }
            prototypeProperty = (value != null) ? value : UniqueTag.NULL_VALUE;
            prototypePropertyAttributes = DONTENUM | PERMANENT | READONLY;
        }


        public virtual int getArity() { return 0; }

        public virtual int getLength() { return 0; }

        public virtual String getFunctionName()
        {
            return "";
        }

        public override string getInstanceIdName(int id)
        {
            switch (id)
            {
                case Id_length: return "length";
                case Id_arity: return "arity";
                case Id_name: return "name";
                case Id_prototype: return "prototype";
                case Id_arguments: return "arguments";
            }
            return base.getInstanceIdName(id);
        }

        public override object getInstanceIdValue(int id)
        {
            switch (id)
            {
                case Id_length: return ScriptRuntime.wrapInt(getLength());
                case Id_arity: return ScriptRuntime.wrapInt(getArity());
                case Id_name: return getFunctionName();
                case Id_prototype: return getPrototypeProperty();
                case Id_arguments: return getArguments();
            }
            return base.getInstanceIdValue(id);
        }
        private static Object jsConstructor(Context cx, Scriptable scope,
                                        Object[] args)
        {
            int arglen = args.Length;
            StringBuilder sourceBuf = new StringBuilder();

            sourceBuf.Append("function ");
            /* version != 1.2 Function constructor behavior -
             * print 'anonymous' as the function name if the
             * version (under which the function was compiled) is
             * less than 1.2... or if it's greater than 1.2, because
             * we need to be closer to ECMA.
             */
            if (cx.getLanguageVersion() != Context.VERSION_1_2)
            {
                sourceBuf.Append("anonymous");
            }
            sourceBuf.Append('(');

            // Append arguments as coma separated strings
            for (int i = 0; i < arglen - 1; i++)
            {
                if (i > 0)
                {
                    sourceBuf.Append(',');
                }
                sourceBuf.Append(ScriptRuntime.toString(args[i]));
            }
            sourceBuf.Append(") {");
            if (arglen != 0)
            {
                // append function body
                String funBody = ScriptRuntime.toString(args[arglen - 1]);
                sourceBuf.Append(funBody);
            }
            sourceBuf.Append('}');
            String source = sourceBuf.ToString();

            int[] linep = new int[1];
            String filename = Context.getSourcePositionFromStack(linep);
            if (filename == null)
            {
                filename = "<eval'ed string>";
                linep[0] = 1;
            }

            String sourceURI = ScriptRuntime.
                makeUrlForGeneratedScript(false, filename, linep[0]);

            Scriptable global = ScriptableObject.getTopLevelScope(scope);

            ErrorReporter reporter;
            reporter = DefaultErrorReporter.forEval(cx.getErrorReporter());

            Evaluator evaluator = Context.createInterpreter();
            if (evaluator == null)
            {
                throw new JavaScriptException("Interpreter not present",
                        filename, linep[0]);
            }

            // Compile with explicit interpreter instance to force interpreter
            // mode.
            return cx.compileFunction(global, source, evaluator, reporter,
                                      sourceURI, 1, null);
        }

        private Object getArguments()
        {
            // <Function name>.arguments is deprecated, so we use a slow
            // way of getting it that doesn't add to the invocation cost.
            // TODO: add warning, error based on version
            Object value = defaultGet("arguments");
            if (value != NOT_FOUND)
            {
                // Should after changing <Function name>.arguments its
                // activation still be available during Function call?
                // This code assumes it should not:
                // defaultGet("arguments") != NOT_FOUND
                // means assigned arguments
                return value;
            }
            Context cx = Context.getContext();
            NativeCall activation = ScriptRuntime.findFunctionActivation(cx, this);
            return (activation == null)
                   ? null
                   : activation.get("arguments", activation);
        }
        public override void setInstanceIdValue(int id, object value)
        {
            if (id == Id_prototype)
            {
                if ((prototypePropertyAttributes & READONLY) == 0)
                {
                    prototypeProperty = (value != null)
                                        ? value : UniqueTag.NULL_VALUE;
                }
                return;
            }
            else if (id == Id_arguments)
            {
                if (value == NOT_FOUND)
                {
                    // This should not be called since "arguments" is PERMANENT
                    Kit.codeBug();
                }
                defaultPut("arguments", value);
            }
            base.setInstanceIdValue(id, value);
        }
        public override void fillConstructorProperties(IdFunctionObject ctor)
        {
            // Fix up bootstrapping problem: getPrototype of the IdFunctionObject
            // can not return Function.prototype because Function object is not
            // yet defined.
            ctor.setPrototype(this);//给当前对象设置prototype
            base.fillConstructorProperties(ctor);
        }
        /// <summary>
        /// 根据id来初始化ptototype的方法
        /// </summary>
        /// <param name="id"></param>
        public override void initPrototypeId(int id)
        {//初始化prototype id
            String s;
            int arity;
            switch (id)
            {
                case Id_constructor: arity = 1; s = "constructor"; break;
                case Id_toString: arity = 1; s = "toString"; break;
                case Id_toSource: arity = 1; s = "toSource"; break;
                case Id_apply: arity = 2; s = "apply"; break;
                case Id_call: arity = 1; s = "call"; break;
                default: throw new ArgumentException(id.ToString());
            }
            initPrototypeMethod(FUNCTION_TAG, id, s, arity);
        }
        private BaseFunction realFunction(Scriptable thisObj, IdFunctionObject f)
        {
            Object x = thisObj.getDefaultValue(ScriptRuntime.FunctionClass);
            if (x is BaseFunction)
            {
                return (BaseFunction)x;
            }
            throw ScriptRuntime.typeError1("msg.incompat.call",
                                           f.getFunctionName());
        }
        public override Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
                             Scriptable thisObj, Object[] args)
        {
            if (!f.hasTag(FUNCTION_TAG))
            {
                return base.execIdCall(f, cx, scope, thisObj, args);
            }
            int id = f.methodId();
            switch (id)
            {
                case Id_constructor:
                    return jsConstructor(cx, scope, args);

                case Id_toString:
                    {
                        BaseFunction realf = realFunction(thisObj, f);
                        int indent = ScriptRuntime.toInt32(args, 0);
                        return realf.decompile(indent, 0);
                    }

                case Id_toSource:
                    {
                        BaseFunction realf = realFunction(thisObj, f);
                        int indent = 0;
                        int flags = Decompiler.TO_SOURCE_FLAG;
                        if (args.Length != 0)
                        {
                            indent = ScriptRuntime.toInt32(args[0]);
                            if (indent >= 0)
                            {
                                flags = 0;
                            }
                            else
                            {
                                indent = 0;
                            }
                        }
                        return realf.decompile(indent, flags);
                    }

                case Id_apply:
                case Id_call:
                    return ScriptRuntime.applyOrCall(id == Id_apply,
                                                     cx, scope, thisObj, args);
            }
            throw new ArgumentException(id.ToString());
        }

        private const int
       Id_constructor = 1,
       Id_toString = 2,
       Id_toSource = 3,
       Id_apply = 4,
       Id_call = 5,

       MAX_PROTOTYPE_ID = 5;

        private Object prototypeProperty;
        private int prototypePropertyAttributes = PERMANENT;

        public Object getPrototypeProperty()
        {
            Object result = prototypeProperty;
            if (result == null)
            {
                lock (this)
                {
                    result = prototypeProperty;
                    if (result == null)
                    {
                        setupDefaultPrototype();
                        result = prototypeProperty;
                    }
                }
            }
            else if (result == UniqueTag.NULL_VALUE) { result = null; }
            return result;
        }


        #region Function Members

        public virtual object call(Context cx, Scriptable scope, Scriptable thisObj, object[] args)
        {
            return Undefined.instance;
        }
        //public Scriptable createObject(Context cx, Scriptable scope)
        //{
        //    Scriptable newInstance = new NativeObject();
        //    newInstance.setPrototype(getClassPrototype());
        //    newInstance.setParentScope(getParentScope());
        //    return newInstance;
        //}
        //public Scriptable construct(Context cx, Scriptable scope, object[] args)
        //{
        //    Scriptable result = createObject(cx, scope);
        //    if (result != null)
        //    {
        //        Object val = call(cx, scope, result, args);
        //        if (val is Scriptable)
        //        {
        //            result = (Scriptable)val;
        //        }
        //    }
        //    else
        //    {
        //        Object val = call(cx, scope, null, args);
        //        if (!(val is Scriptable))
        //        {
        //            // It is program error not to return Scriptable from
        //            // the call method if createObject returns null.
        //            throw new Exception(
        //                "Bad implementaion of call as constructor, name="
        //                + getFunctionName() + " in " + GetType().Name);
        //        }
        //        result = (Scriptable)val;
        //        if (result.getPrototype() == null)
        //        {
        //            result.setPrototype(getClassPrototype());
        //        }
        //        if (result.getParentScope() == null)
        //        {
        //            Scriptable parent = getParentScope();
        //            if (result != parent)
        //            {
        //                result.setParentScope(parent);
        //            }
        //        }
        //    }
        //    return result;
        //}


        #endregion
        public override int findPrototypeId(string s)
        {
            int id;
            // #string_id_map#
            // #generated# Last update: 2007-05-09 08:15:15 EDT
            id = 0; String X = null; int c;
            switch (s.Length)
            {
                case 4: X = "call"; id = Id_call; goto L;
                case 5: X = "apply"; id = Id_apply; goto L;
                case 8: c = s.ToCharArray()[3];
                    if (c == 'o') { X = "toSource"; id = Id_toSource; }
                    else if (c == 't') { X = "toString"; id = Id_toString; }
                    goto L;
                case 11: X = "constructor"; id = Id_constructor; goto L;
            }
        L: ;
            if (X != null && X != s && !(X == s)) id = 0;
            goto L0;


        L0:
            // #/generated#
            return id;
        }

        public virtual String decompile(int indent, int flags)
        {
            StringBuilder sb = new StringBuilder();
            bool justbody = (0 != (flags & Decompiler.ONLY_BODY_FLAG));
            if (!justbody)
            {
                sb.Append("function ");
                sb.Append(getFunctionName());
                sb.Append("() {\n\t");
            }
            sb.Append("[native code, arity=");
            sb.Append(getArity());
            sb.Append("]\n");
            if (!justbody)
            {
                sb.Append("}\n");
            }
            return sb.ToString();
        }

        public Scriptable getClassPrototype()
        {
            Object protoVal = getPrototypeProperty();
            if (protoVal is Scriptable)
            {
                return (Scriptable)protoVal;
            }
            return getClassPrototype(this, "Object");
        }

        private void setupDefaultPrototype()
        {
            NativeObject obj = new NativeObject();
            int attr = ScriptableObject.DONTENUM;
            obj.defineProperty("constructor", this, attr);
            // put the prototype property into the object now, then in the
            // wacky case of a user defining a function Object(), we don't
            // get an infinite loop trying to find the prototype.
            prototypeProperty = obj;
            Scriptable proto = getObjectPrototype(this);
            if (proto != obj)
            {
                // not the one we just made, it must remain grounded
                obj.setPrototype(proto);
            }
        }


        public virtual Scriptable createObject(Context cx, Scriptable scope)
        {
            Scriptable newInstance = new NativeObject();
            newInstance.setPrototype(getClassPrototype());
            newInstance.setParentScope(getParentScope());
            return newInstance;
        }

        public static bool isApply(IdFunctionObject f)
        {
            return f.hasTag(FUNCTION_TAG) && f.methodId() == Id_apply;
        }

        public static bool isApplyOrCall(IdFunctionObject f)
        {
            if (f.hasTag(FUNCTION_TAG))
            {
                switch (f.methodId())
                {
                    case Id_apply:
                    case Id_call:
                        return true;
                }
            }
            return false;
        }

        public virtual Scriptable construct(Context cx, Scriptable scope, Object[] args)
        {
            Scriptable result = createObject(cx, scope);
            if (result != null)
            {
                Object val = call(cx, scope, result, args);
                if (val is Scriptable)
                {
                    result = (Scriptable)val;
                }
            }
            else
            {
                Object val = call(cx, scope, null, args);
                if (!(val is Scriptable))
                {
                    // It is program error not to return Scriptable from
                    // the call method if createObject returns null.
                    throw new Exception(
                        "Bad implementaion of call as constructor, name="
                        + getFunctionName() + " in " + GetType().Name);
                }
                result = (Scriptable)val;
                if (result.getPrototype() == null)
                {
                    result.setPrototype(getClassPrototype());
                }
                if (result.getParentScope() == null)
                {
                    Scriptable parent = getParentScope();
                    if (result != parent)
                    {
                        result.setParentScope(parent);
                    }
                }
            }
            return result;
        }
    }//end for class
}
